package net.vinote.smart.platform.module.database.bo;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;

import net.vinote.smart.platform.module.log.RunLogger;

import org.json.JSONException;
import org.json.JSONObject;

public class BizObject {
	private static final RunLogger logger = RunLogger.getLogger();
	private Map<String, Object> attribute = new HashMap<String, Object>();

	public String getAttribute(String key) {
		Object o = attribute.get(key.toUpperCase());
		return o == null ? null : o.toString();
	}

	public void setAttribute(String key, String val) {
		setattribute(key, val);
	}

	private void setattribute(String key, Object val) {
		attribute.put(key.toUpperCase(), val);
	}

	public Set<String> getAttributeNames() {
		return attribute.keySet();
	}

	public boolean containsKey(String key) {
		return attribute.containsKey(key.toUpperCase());
	}

	public JSONObject getJSON() {
		JSONObject json = new JSONObject();
		try {
			for (Entry<String, Object> entry : attribute.entrySet()) {
				json.put(entry.getKey(), entry.getValue());
			}
		} catch (JSONException e) {
			logger.log(Level.WARNING, e.getMessage(), e);
		}
		return json;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer(this.getClass().getSimpleName()
				+ "[\r\n");
		for (Field f : this.getClass().getDeclaredFields()) {
			try {
				sb.append(f.getName()).append(":").append(f.get(this))
						.append("\r\n");
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		sb.append("]");
		return sb.toString();
	}
}
